package com.mcc.web.controller.system;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.mcc.common.core.domain.TreeSelect;
import com.mcc.common.exception.CustomException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mcc.common.annotation.Log;
import com.mcc.common.constant.Constants;
import com.mcc.common.constant.UserConstants;
import com.mcc.common.core.controller.BaseController;
import com.mcc.common.core.domain.AjaxResult;
import com.mcc.common.core.domain.entity.SysMenu;
import com.mcc.common.core.domain.model.LoginUser;
import com.mcc.common.enums.BusinessType;
import com.mcc.common.utils.SecurityUtils;
import com.mcc.common.utils.ServletUtils;
import com.mcc.common.utils.StringUtils;
import com.mcc.framework.web.service.TokenService;
import com.mcc.system.service.ISysMenuService;

/**
 * 菜单信息
 *
 * @author gxy
 */
@Api(tags = "菜单")
@ApiSort(12)
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private TokenService tokenService;

    @ApiOperation("获取菜单列表")
    @ApiOperationSupport(order = 1)
    @PreAuthorize("@ss.hasPermi('system:menu:list')")
    @GetMapping("/list")
    public AjaxResult<List<SysMenu>> list(SysMenu menu) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return AjaxResult.success(menus);
    }

    @ApiOperation("根据菜单编号获取详细信息")
    @ApiOperationSupport(order = 2)
    @PreAuthorize("@ss.hasPermi('system:menu:query')")
    @GetMapping("/get/{menuId}")
    public AjaxResult<SysMenu> getInfo(@PathVariable Long menuId) {
        return AjaxResult.success(menuService.selectMenuById(menuId));
    }

    @ApiOperation("获取菜单下拉树列表")
    @ApiOperationSupport(order = 3)
    @GetMapping("/treeselect")
    public AjaxResult<List<TreeSelect>> treeselect(SysMenu menu) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
    }

    @ApiOperation("加载对应角色菜单列表树")
    @ApiOperationSupport(order = 4)
    @GetMapping("/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable Long roleId) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<SysMenu> menus = menuService.selectMenuList(loginUser.getUser().getUserId());
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        data.put("menus", menuService.buildMenuTreeSelect(menus));
        return AjaxResult.success(data);
    }

    @ApiOperation("新增菜单")
    @ApiOperationSupport(order = 5)
    @PreAuthorize("@ss.hasPermi('system:menu:add')")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysMenu menu) {
        if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            throw new CustomException("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        menu.setCreateTime(new Date());
        return toAjax(menuService.insertMenu(menu));
    }

    @ApiOperation("修改菜单")
    @ApiOperationSupport(order = 6)
    @PreAuthorize("@ss.hasPermi('system:menu:edit')")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody SysMenu menu) {
        if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            throw new CustomException("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            throw new CustomException("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        menu.setUpdateTime(new Date());
        return toAjax(menuService.updateMenu(menu));
    }

    @ApiOperation("删除菜单")
    @ApiOperationSupport(order = 7)
    @PreAuthorize("@ss.hasPermi('system:menu:remove')")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{menuId}")
    public AjaxResult remove(@PathVariable Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            throw new CustomException("存在子菜单,不允许删除");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }
}
